import type { Validate } from "./validate"
export function getApiJson(str: string) {
    const a = str.slice(str.indexOf("exportconstmain:"))
    const b = a.slice(a.indexOf("={") + 1)
    const c = b.slice(0, b.indexOf("handler:") - 1) + "}"
    return eval("(" + c + ")")
}
export function getProto(protoList: any): Validate[] {
    const { type, properties = [] } = protoList
    let array: Validate[] = []
    if (type === "Interface") { // 接口必须为对象格式
        for (let i = 0, len = properties.length; i < len; i++) { //循环接口对象属性
            const properties_item = properties[i]
            array.push(generatorTovalidate(properties_item))
        }
    }
    return array
}

export function generatorTovalidate(generator: any) {
    const { name, type, optional } = generator
    const { type: item_type, elementType, properties, members, comment } = type
    let validate: Validate = {
        key: name,
        type: item_type === 'Interface' ? 'object' : item_type.toLowerCase(),
        requred: !optional
    };
    // 注释处理
    if (comment) {
        const commentArray = comment.split("\n")
        commentArray.forEach((commentItem: any) => {
            // 最大长度
            if (commentItem.indexOf('max:') === 0) {
                validate.max = Number(commentItem.slice(4))
            }
            // 最小长度
            if (commentItem.indexOf('min:') === 0) {
                validate.min = Number(commentItem.slice(4))
            }
            // 格式
            if (commentItem.indexOf('format:') === 0) {
                validate.format = commentItem.slice(7)
            }
        });
    }
    // 对象
    if (item_type === 'Interface') {
        validate.object_validate = properties.map((item: any) => {
            return generatorTovalidate(item)
        })
    }
    // 元组
    if (item_type === 'Union') {
        if (members.every((item: any) => item.type.type === 'Literal')) {
            validate.includes = members.map((item: any) => item.type.literal)
        }
    }
    // 数组
    if (item_type === 'Array') {
        if (elementType.type === 'String') {
            validate.ArrayString = true
        }
        if (elementType.type === 'Number') {
            validate.ArrayNumber = true
        }
        if (elementType.type === 'Interface') {
            validate.ArrayObject = true
            validate.object_validate = elementType.properties.map((item: any) => {
                return generatorTovalidate(item)
            })
        }
    }
    return validate
}